package com.lanchuan.soft.controller;

import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;

@RequestMapping("test")
@Controller
@Log4j2
public class TestController {

    @RequestMapping("download")
    public void download(HttpServletResponse response, String path) {
        InputStream in;
        OutputStream out = null;
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();

            // 获取网络文件
            URL url = new URL(path);
            in = new BufferedInputStream(url.openStream());
            // 创建数据缓冲区
            byte[] buffer = new byte[in.available()];
            // 下载文件设置
            response.setContentType("application/octet-stream;charset=utf-8");
            //设置content-disposition响应头控制浏览器以下载的形式打开文件
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + buffer.length);
            // 获取要下载的文件输入流
            // 通过response对象获取outputStream流
            out = response.getOutputStream();
            out.write(buffer);
            out.flush();
            in.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
